package handler

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"markedit/internal/model"
	"markedit/internal/service"
)

type ExportHandler struct {
	exportService *service.ExportService
	fileService   *service.FileService
	logger        *logrus.Logger
}

func NewExportHandler(exportService *service.ExportService, fileService *service.FileService, logger *logrus.Logger) *ExportHandler {
	return &ExportHandler{
		exportService: exportService,
		fileService:   fileService,
		logger:        logger,
	}
}

// ExportToPDF 导出为PDF
// @Summary 导出为PDF
// @Description 将Markdown文档导出为PDF文件
// @Tags Export
// @Accept json
// @Produce application/pdf
// @Param request body model.ExportRequest true "导出请求"
// @Success 200 {file} binary "PDF文件"
// @Failure 400 {object} model.ErrorResponse
// @Router /api/export/pdf [post]
func (h *ExportHandler) ExportToPDF(c *gin.Context) {
	var request model.ExportRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		h.logger.Errorf("Failed to bind request: %v", err)
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Invalid request body",
			Message: err.Error(),
		})
		return
	}

	// 获取文档内容
	var doc *model.Document
	var err error
	
	if request.DocumentID != "" {
		// 从数据库获取文档
		doc, err = h.fileService.GetDocument(request.DocumentID)
		if err != nil {
			h.logger.Errorf("Failed to get document %s: %v", request.DocumentID, err)
			c.JSON(http.StatusNotFound, model.ErrorResponse{
				Error:   "Document not found",
				Message: err.Error(),
			})
			return
		}
	} else if request.Content != "" {
		// 使用直接传递的内容
		doc = &model.Document{
			ID:      "temp",
			Title:   "Exported Document",
			Content: request.Content,
		}
	} else {
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Missing content",
			Message: "Either document_id or content must be provided",
		})
		return
	}

	pdfData, err := h.exportService.ExportToPDF(doc, request.Settings)
	if err != nil {
		h.logger.Errorf("Failed to export to PDF: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to export to PDF",
			Message: err.Error(),
		})
		return
	}

	filename := request.Filename
	if filename == "" {
		filename = "document.pdf"
	}

	c.Header("Content-Type", "application/pdf")
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.Header("Content-Length", strconv.Itoa(len(pdfData)))
	c.Data(http.StatusOK, "application/pdf", pdfData)
}

// ExportToWord 导出为Word
// @Summary 导出为Word
// @Description 将Markdown文档导出为Word文件
// @Tags Export
// @Accept json
// @Produce application/vnd.openxmlformats-officedocument.wordprocessingml.document
// @Param request body model.ExportRequest true "导出请求"
// @Success 200 {file} binary "Word文件"
// @Failure 400 {object} model.ErrorResponse
// @Router /api/export/word [post]
func (h *ExportHandler) ExportToWord(c *gin.Context) {
	var request model.ExportRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		h.logger.Errorf("Failed to bind request: %v", err)
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Invalid request body",
			Message: err.Error(),
		})
		return
	}

	// 获取文档内容
	var doc *model.Document
	var err error
	
	if request.DocumentID != "" {
		// 从数据库获取文档
		doc, err = h.fileService.GetDocument(request.DocumentID)
		if err != nil {
			h.logger.Errorf("Failed to get document %s: %v", request.DocumentID, err)
			c.JSON(http.StatusNotFound, model.ErrorResponse{
				Error:   "Document not found",
				Message: err.Error(),
			})
			return
		}
	} else if request.Content != "" {
		// 使用直接传递的内容
		doc = &model.Document{
			ID:      "temp",
			Title:   "Exported Document",
			Content: request.Content,
		}
	} else {
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Missing content",
			Message: "Either document_id or content must be provided",
		})
		return
	}

	wordData, err := h.exportService.ExportToWord(doc, request.Settings)
	if err != nil {
		h.logger.Errorf("Failed to export to Word: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to export to Word",
			Message: err.Error(),
		})
		return
	}

	filename := request.Filename
	if filename == "" {
		filename = "document.docx"
	}

	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.Header("Content-Length", strconv.Itoa(len(wordData)))
	c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", wordData)
}

// ExportToHTML 导出为HTML
// @Summary 导出为HTML
// @Description 将Markdown文档导出为HTML文件
// @Tags Export
// @Accept json
// @Produce text/html
// @Param request body model.ExportRequest true "导出请求"
// @Success 200 {string} string "HTML内容"
// @Failure 400 {object} model.ErrorResponse
// @Router /api/export/html [post]
func (h *ExportHandler) ExportToHTML(c *gin.Context) {
	var request model.ExportRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		h.logger.Errorf("Failed to bind request: %v", err)
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Invalid request body",
			Message: err.Error(),
		})
		return
	}

	// 获取文档内容
	var doc *model.Document
	var err error
	
	if request.DocumentID != "" {
		// 从数据库获取文档
		doc, err = h.fileService.GetDocument(request.DocumentID)
		if err != nil {
			h.logger.Errorf("Failed to get document %s: %v", request.DocumentID, err)
			c.JSON(http.StatusNotFound, model.ErrorResponse{
				Error:   "Document not found",
				Message: err.Error(),
			})
			return
		}
	} else if request.Content != "" {
		// 使用直接传递的内容
		doc = &model.Document{
			ID:      "temp",
			Title:   "Exported Document",
			Content: request.Content,
		}
	} else {
		c.JSON(http.StatusBadRequest, model.ErrorResponse{
			Error:   "Missing content",
			Message: "Either document_id or content must be provided",
		})
		return
	}

	htmlContent, err := h.exportService.ExportToHTML(doc, request.Settings)
	if err != nil {
		h.logger.Errorf("Failed to export to HTML: %v", err)
		c.JSON(http.StatusInternalServerError, model.ErrorResponse{
			Error:   "Failed to export to HTML",
			Message: err.Error(),
		})
		return
	}

	filename := request.Filename
	if filename == "" {
		filename = "document.html"
	}

	c.Header("Content-Type", "text/html; charset=utf-8")
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.String(http.StatusOK, string(htmlContent))
}